<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加类型"
    width="500px"
    :before-close="closeDialog"
    center
    top="30vh"
    destroy-on-close
  >
    <el-form ref="typeFormRef" :model="typeForm" label-width="120px">
      <el-form-item label="文章类型名称：">
        <el-input v-model="typeForm.typeName"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitForm"> 确定 </el-button>
        <el-button @click="closeDialog">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import {
  addArticleTypeApi,
  findArticleTypeApi,
  updateArticleTypeApi,
} from '@/api/article'
const emit = defineEmits(['getArticleTypeList'])

let typeForm = reactive({
  typeName: '',
  id: '',
})
const typeFormRef = ref()
const dialogVisible = ref(false) // 是否显示提交文章分类表单的弹框

const closeDialog = (done: any) => {
  ElMessageBox.confirm('你确认要关闭弹框吗?', {
    confirmButtonText: '是',
    cancelButtonText: '否',
  })
    .then(() => {
      clearForm()
      done()
    })
    .catch(() => {})
}

// 清除表单数据并移除校验结果
const clearForm = () => {
  dialogVisible.value = false
  typeForm.typeName = ''

  typeForm.id = ''
  typeFormRef.value.clearValidate()
}

// 显示提交分类表单的弹框
const showDialog = async (id: any) => {
  if (id) {
    let res: any = await findArticleTypeApi(id)
    if (res.status == 0) {
      typeForm.typeName = res.data.typeName

      typeForm.id = res.data.id
    }
  }
  dialogVisible.value = true
}

// 提交文章分类表单
const submitForm = async () => {
  let request = null
  if (typeForm.id) {
    request = updateArticleTypeApi
  } else {
    request = addArticleTypeApi
  }
  let res: any = await request(typeForm)
  if (res.status == 0) {
    ElMessage.success(`${typeForm.id ? '修改' : '添加'}文章类型成功`)
    clearForm()
    emit('getArticleTypeList')
  }
}

defineExpose({
  showDialog,
})
</script>
<style lang="scss" scoped>
.el-form-item {
  display: flex;
  margin-right: 0;
  margin-bottom: 18px;
}
</style>
